package com.fs.base.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import com.fs.base.pojo.PkEntity;
import com.fs.base.vo.SortDto;

/**
 * @author TiddlerCJ
 * @desc 分页助手
 */
public class PageHeper {
	private final static int FIRST_PAGE = 1; 
	private final static int DEFAULT_PAGE_SIZE = 10; 
	
	private static String PAGE = "page"; 
	private static String PAGE_SIZE = "rows"; 
	private static String SORT = "sort"; 
	private static String ORDER = "order"; 
	
	/**
	 * 是否分页
	 * @param request
	 * @return
	 */
	public static boolean isPage(HttpServletRequest request){
		Boolean flag = true;
		if(StringUtils.isBlank(request.getParameter(PAGE)) && 
				StringUtils.isBlank(request.getParameter(PAGE_SIZE))){
			flag = false;
		}
		return flag;
		
	}
	
	/**
	 * @param request
	 * @return
	 */
	public static PageRequest pageRequest(HttpServletRequest request){
		int page = FIRST_PAGE ;
		int size = DEFAULT_PAGE_SIZE ;
		
		if(StringUtils.isNotBlank(request.getParameter(PAGE))){
			page = Integer.parseInt(request.getParameter(PAGE));
		}
		if(StringUtils.isNotBlank(request.getParameter(PAGE_SIZE))){
			size = Integer.parseInt(request.getParameter(PAGE_SIZE));
		}
		/*
		 * 列表排序
		 */
		Sort _sort = sort(request);
		if(_sort!=null){
			return new PageRequest(page-1, size, _sort);  
		}
		return new PageRequest(page-1, size);
	}
	
	/**
	 * 返回排序对象
	 * @param request
	 * @return
	 */
	public static Sort sort(HttpServletRequest request){
		String orderField = request.getParameter(SORT);
		String orderType = request.getParameter(ORDER);
		Sort _sort = null;
		if(StringUtils.isNotBlank(orderField)){
			_sort = sort(orderType, orderField);
		}else{
			_sort = sort("desc", "createTime");
		}
		return _sort;
	}
	
	/*
	 * 组合排序
	 */
	public static Sort sort(SortDto... dtos) {
	    Sort result = null;
	    for(int i=0; i<dtos.length; i++) {
	        SortDto dto = dtos[i];
	        if(result == null) {
	            result = new Sort(Sort.Direction.fromString(dto.getOrder()), dto.getSort());
	        } else {
	            result = result.and(new Sort(Sort.Direction.fromString(dto.getOrder()), dto.getSort()));
	        }
	    }
	    return result;
	}
	
	/**
	 * 默认排序
	 * @return
	 */
	public static Sort sort() {
		return sort("asc", PkEntity.PRIMARY_KEY_NAME);
    }

	/**
	 * 单个排序
	 * @param orderType
	 * @param orderField
	 * @return
	 */
    public static Sort sort(String orderType, String orderField) {
    	if(StringUtils.isBlank(orderType)) orderType = "asc";
    	return new Sort(Sort.Direction.fromString(orderType), orderField);
    }
	
}
